<?php
namespace PFT\Hotel;
 /**
  * 【票付通】凭证号:{code}，您已成功购买了【{dname}】{pname}:{tnum}间，
  * 入住时间:{begintime}，离店时间:{endtime}，取票信息:{getaddr}，此为凭证，请妥善保管。
  * 详情及二维码:{link}
  */
class HotelSms {
    private $order_tel;
    private $aid;
    private $fid;
    private $tid;
    private $pid;
    private $p_type;
    private $order_num;
    private $soap;
    private $db = null;
    private $source_apply_did;

    const SMS_CONTENT_TPL = '凭证号:{code}，您成功购买{pname}:{tnum}间，入住日期:{begintime}，离店日期:{endtime}。此为凭证，请妥善保管。详情及二维码:{link}';

    //【票付通】入住凭证：123456。您成功购买郁金香高级客房：3间，入住日期3月18日，离店日期3月22日。
//此为凭证，请妥善保管。详情及二维码:http://12301.cc/3u5235
//发给供应商的短信：

    public function __construct(\SoapClient $soap)
    {
        $this->soap = $soap;
        $this->db  = $this->db();
    }

    private function db()
    {
        $dsn = "mysql:dbname=myuu;host=127.0.0.1;port=3306";
        $pdo = new \PDO($dsn, 'wsdl', 'ws*753951');
        $pdo->exec('SET NAMES "UTF8"');
        return $pdo;
    }

    private function GetApplyDid($lid)
    {
        $sql = "SELECT apply_did,p_type FROM uu_land WHERE id=$lid LIMIT 1";
//        echo $sql, '<br>',PHP_EOL;
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        return $stmt->fetch(\PDO::FETCH_NUM);
    }

    /**
     * 设置参数
     *
     * @param $order_tel
     * @param $aid
     * @param $fid
     * @param $tid
     * @param $pid
     * @param $order_num
     * @param $lid
     */
    public function SetParam($order_tel, $aid, $fid, $tid, $pid, $order_num, $lid)
    {
        $this->order_tel = (string)$order_tel;
        $this->aid = (int)$aid;
        $this->fid = (int)$fid;//$mainOrder['UUmid'];
        $this->tid = (int)$tid;//$mainOrder['UUtid'];
        $this->pid = (int)$pid;//$mainOrder['UUpid'];
        $this->order_num = (string)$order_num;//$mainOrder['UUordernum'];
//        list($this->source_apply_did, $this->p_type) = $this->GetApplyDid((int)$lid);
        list($this->source_apply_did, $this->p_type) = $this->GetApplyDid((int)$lid);
//        print_r($ret);
//        echo $this->p_type = $ret['p_type'];
    }

    private function SmsContent($p_name, $num, $begin_time, $end_time)
    {
        $search_replace = array();
        //获取凭证号
        $cert_xml = $this->soap->Terminal_Code_Verify( $this->order_num,1, 1);
//        echo $cert_xml;
//        exit;
        $cert_obj = simplexml_load_string($cert_xml);
        $search_replace['{code}'] = (string)$cert_obj->Rec->UUcode;

        $str="select dname from pft_member where id='$this->aid' LIMIT 1";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $search_replace['{dname}'] = $GLOBALS['le']->f('dname');
        $search_replace['{pname}'] = $p_name;
        $search_replace['{tnum}']  = $num;
        $search_replace['{begintime}']  = $begin_time;
        $search_replace['{endtime}']  = $end_time;

        $str="select getaddr from uu_jq_ticket where id='$this->tid' LIMIT 1";
        $stmt = $this->db->prepare($str);
        $stmt->execute();
        $search_replace['{getaddr}'] = $stmt->fetchColumn(0);
        $search_replace['{link}'] = "http://12301.cc/".url_sms($this->order_num);

        $sendmsg=str_replace( array_keys($search_replace),
            array_values($search_replace), self::SMS_CONTENT_TPL);

        $sendmsg=trim($sendmsg);
        $sendmsg=str_replace(array(" ","　"),array("",""),$sendmsg);
        return $sendmsg;
    }

    private function SendSms($sendMsg)
    {
        list($cformat, $ptype, $sms_account) = $this->GetSmsAccount($this->pid, $this->aid);
        //使用集时通发送短信
        if (isset($sms_account) && $sms_account) $Taccount=$sms_account;
        else $Taccount='';
        $num = $this->soap->Send_SMS_V($this->order_tel, $sendMsg, -1, $Taccount);
        //记录短信发送信息
        $times_num=($num==100)?1:0;
        $str="select id from sms_order where ordernum='{$this->order_num}' limit 1";
        $stmt = $this->db->prepare($str);
        $stmt->execute();
        if ($stmt->fetchColumn(0)) {
            $str=<<<SQL
update sms_order set times=times+{$times_num},last_time=now(),
ordertel='{$this->order_tel}',smstxt='{$sendMsg}',
fid={$this->fid},aid={$this->aid} where ordernum='{$this->order_num}' LIMIT 1
SQL;
        }
        else {
            $str=<<<SQL
insert sms_order set times=times+{$times_num},last_time=now(),
ordertel='{$this->order_tel}',smstxt='{$sendMsg}',
fid={$this->fid},aid={$this->aid}
SQL;
        }
        echo $str,'<br/>';
        $this->db->exec($str);

        $msgLen = str_len2($sendMsg);
        $this->LogMoney($msgLen, $num);

        if ($num>0) {
            $str="update uu_ss_order set remsg=remsg+1 where ordernum='$this->order_num' limit 1";
            echo $str,'<br/>';
            $this->db->exec($str);
            return 100;
        }else{
            $str="update uu_ss_order set smserror='$num' where ordernum='$this->order_num' limit 1";
            echo $str,'<br/>';
            $this->db->exec($str);
            return $num;
        }
    }

    public function Send($p_name, $num, $begin_time, $end_time)
    {
//        $this->SetParam($param);
        $sms_content = $this->SmsContent($p_name, $num, $begin_time, $end_time);
//        echo $sms_content;
//        exit;
        return $this->SendSms($sms_content);
    }

//
    public function SendByOrderInfo(Array $order)
    {
        $this->SetParam(
            $order['mainOrder']->UUordertel,
            $order['mainOrder']->UUaid,
            $order['mainOrder']->UUfid,
            $order['mainOrder']->UUtid,
            $order['mainOrder']->UUpid,
            $order['mainOrder']->UUordernum,
            $order['mainOrder']->UUlid
        );
//        return 'aaa';
        //非酒店类型的订单
        if ($this->p_type !='C') {
//            return $this->soap->reSend_SMS_Global_PL($this->order_num,$this->aid,$this->fid);//重发短信
        }
//        $order=$obj->info();
//        if ($order['mainOrder']->UUremsg>3) {
//            return 116;
//        }
        $time_list = array();
        if (count($order['childOrder'])>0) {
            foreach ($order['childOrder'] as $child) {
                $time_list[] = (string)$child->UUbegintime;
            }
        } else {
            $time_list[] = (string)$order['mainOrder']->UUbegintime;
            $time_list[] = (string)$order['mainOrder']->UUbegintime;
        }
        sort($time_list);
        $in_time = array_shift($time_list);
        $out_time= array_pop($time_list);
        $p_name  = strval($order['mainOrder']->UUltitle . $order['mainOrder']->UUttitle);
        echo "in_time=$in_time,out_time=$out_time,p_name=$p_name";
        return $this->Send($p_name, intval($order['mainOrder']->UUtnum), $in_time, $out_time);
    }

    private function GetSmsAccount()
    {
        $str="select cformat,ptype,sms_account from uu_sms_format"
            ." where pid='{$this->pid}' or aid='{$this->source_apply_did}'"
            ." order by aid desc limit 1";
        $stmt = $this->db->prepare($str);
        $stmt->execute();
        return $stmt->fetch(\PDO::FETCH_NUM);
    }

    private function LogMoney($msglen, $num)
    {
        //扣除短信费用
        if ($num==100){
            $m=ceil($msglen/66);
            $str="select fee_sms,fee_pay_way from pft_member where id=? limit 1";
            echo $str,'<br/>',PHP_EOL;
            $stmt = $this->db->prepare($str);
            $stmt->execute(array($this->source_apply_did));
            $FeeConf = $stmt->fetch(\PDO::FETCH_ASSOC);

            $fee_sms=$FeeConf['fee_sms'];
            $fee_pay_way=$FeeConf['fee_pay_way'];
            $dmoney=$fee_sms*$m;

            $fee_member=($fee_pay_way==1)? $this->fid : $this->source_apply_did;

            $str="update pft_member_money set amoney=amoney-$dmoney where fid=$fee_member LIMIT 1";
            echo $str,'<br/>',PHP_EOL;
            $this->db->exec($str);

            $str="select amoney from pft_member_money where fid=$fee_member limit 1";
            echo $str,'<br/>',PHP_EOL;
            $stmt = $this->db->prepare($str);
            $stmt->execute();
            $lmoney=$stmt->fetchColumn(0);

            $str="insert pft_member_journal set fid=$fee_member,dmoney=$dmoney,lmoney=$lmoney,orderid='$this->order_num',daction=1,rectime=now(),dtype=8,ptype=0";
            echo $str,'<br/>',PHP_EOL;
            $this->db->exec($str);

            //平台流水帐
            $str="update pft_member_money set amoney=amoney+$dmoney where fid=1";
            echo $str,'<br/>',PHP_EOL;
            $this->db->exec($str);
            $str="select amoney from pft_member_money where fid=1 limit 1";
            echo $str,'<br/>',PHP_EOL;
            $stmt = $this->db->prepare($str);
            $stmt->execute();
            $lmoney=$stmt->fetchColumn(0);
            $str="insert pft_member_journal set fid=1,dmoney=$dmoney,lmoney=$lmoney,orderid='$this->order_num',daction=0,rectime=now(),dtype=8,ptype=0";
            echo $str,'<br/>',PHP_EOL;
            $this->db->exec($str);
        }
    }
}


/*
$a1=array('"{dname}","{pname}","{tnum}","{code}","{begintime}","{getaddr}","{sphone}","{place}","{time}","{link}"');
*/



function url_sms($n)
{
    $na=array("u","l","5","4","3","2","1","y","s","t");
    $n=(string)$n;
    $s="";
    $len=strlen($n);
    for ($i=0;$i<$len;$i++){
        $s.=$na[$n{$i}];
    }
    return $s;
}

if (!function_exists('str_len2')) {
    function str_len2($str)
    {
        $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));

        if ($length)
        {
            return strlen($str) - $length + intval($length / 3);
        }
        else
        {
            return strlen($str);
        }
    }
}
$pid = 9147;
$aid = 113;
$fid = 113;
$tid = 12059;
$order_num = '867077';
include '/var/www/html/new/com.inc.php';
include '../../class/SoapInit.class.php';
include("/var/www/html/new/d/class/OrderRecord.php");
$soap = \SoapInit::GetSoapInside();
$obj = new HotelSms($soap, '18059004030', '867077',$aid, $tid, $fid, $pid);
//$obj->Send('【pzp测试】0123酒店B',3,'2015-03-18','2015-03-26');
$or = new \OrderRecord($order_num, $soap);
$order = $or->info();
//print_r($order);
$obj->SendByOrderInfo($order);
?>    